//
//  ViewController.swift
//  键盘监听
//
//  Created by zzzzzzzzzz on 2025/3/11.
//

import Cocoa

class ViewController: NSViewController {
    
    // 添加两个文本输入框和标签
    private var findTextField: NSTextField!
    private var replaceTextField: NSTextField!
    private var findTextField2: NSTextField!
    private var replaceTextField2: NSTextField!
    private var statusLabel: NSTextField!
    
    // 添加开关控制和替换模式选择
    private var monitoringEnabledCheckbox: NSButton!
    private var replaceAllCheckbox: NSButton!
    private var isMonitoringEnabled: Bool = true
    private var replaceAllOccurrences: Bool = true
    
    // 剪贴板监听计时器
    private var clipboardTimer: Timer?
    private var lastChangeCount: Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置UI界面
        setupUI()
        
        // 开始监听剪贴板
        startClipboardMonitoring()
    }
    
    private func setupUI() {
        // 创建查找文本标签
        let findLabel = NSTextField(labelWithString: "查找内容:")
        findLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(findLabel)
        
        // 创建查找文本输入框
        findTextField = NSTextField()
        findTextField.placeholderString = "输入要查找的文本"
        findTextField.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(findTextField)
        
        // 创建替换文本标签
        let replaceLabel = NSTextField(labelWithString: "替换内容:")
        replaceLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(replaceLabel)
        
        // 创建替换文本输入框
        replaceTextField = NSTextField()
        replaceTextField.placeholderString = "输入要替换的文本"
        replaceTextField.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(replaceTextField)
        
        // 创建第二组查找文本标签
        let findLabel2 = NSTextField(labelWithString: "查找内容2:")
        findLabel2.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(findLabel2)
        
        // 创建第二组查找文本输入框
        findTextField2 = NSTextField()
        findTextField2.placeholderString = "输入要查找的文本"
        findTextField2.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(findTextField2)
        
        // 创建第二组替换文本标签
        let replaceLabel2 = NSTextField(labelWithString: "替换内容2:")
        replaceLabel2.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(replaceLabel2)
        
        // 创建第二组替换文本输入框
        replaceTextField2 = NSTextField()
        replaceTextField2.placeholderString = "输入要替换的文本"
        replaceTextField2.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(replaceTextField2)
        
        // 创建监听开关复选框
        monitoringEnabledCheckbox = NSButton(checkboxWithTitle: "启用剪贴板监听", target: self, action: #selector(toggleMonitoring))
        monitoringEnabledCheckbox.translatesAutoresizingMaskIntoConstraints = false
        monitoringEnabledCheckbox.state = .on
        view.addSubview(monitoringEnabledCheckbox)
        
        // 创建替换模式复选框
        replaceAllCheckbox = NSButton(checkboxWithTitle: "替换所有匹配项", target: self, action: #selector(toggleReplaceMode))
        replaceAllCheckbox.translatesAutoresizingMaskIntoConstraints = false
        replaceAllCheckbox.state = .on
        view.addSubview(replaceAllCheckbox)
        
        // 创建状态标签
        statusLabel = NSTextField(labelWithString: "剪贴板监听已启动")
        statusLabel.translatesAutoresizingMaskIntoConstraints = false
        statusLabel.textColor = .systemGreen
        view.addSubview(statusLabel)
        
        // 设置约束
        NSLayoutConstraint.activate([
            // 查找标签约束
            findLabel.topAnchor.constraint(equalTo: view.topAnchor, constant: 30),
            findLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            findLabel.widthAnchor.constraint(equalToConstant: 80),
            
            // 查找输入框约束
            findTextField.topAnchor.constraint(equalTo: findLabel.topAnchor),
            findTextField.leadingAnchor.constraint(equalTo: findLabel.trailingAnchor, constant: 10),
            findTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            
            // 替换标签约束
            replaceLabel.topAnchor.constraint(equalTo: findLabel.bottomAnchor, constant: 20),
            replaceLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            replaceLabel.widthAnchor.constraint(equalToConstant: 80),
            
            // 替换输入框约束
            replaceTextField.topAnchor.constraint(equalTo: replaceLabel.topAnchor),
            replaceTextField.leadingAnchor.constraint(equalTo: replaceLabel.trailingAnchor, constant: 10),
            replaceTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            
            // 第二组查找标签约束
            findLabel2.topAnchor.constraint(equalTo: replaceLabel.bottomAnchor, constant: 20),
            findLabel2.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            findLabel2.widthAnchor.constraint(equalToConstant: 80),
            
            // 第二组查找输入框约束
            findTextField2.topAnchor.constraint(equalTo: findLabel2.topAnchor),
            findTextField2.leadingAnchor.constraint(equalTo: findLabel2.trailingAnchor, constant: 10),
            findTextField2.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            
            // 第二组替换标签约束
            replaceLabel2.topAnchor.constraint(equalTo: findLabel2.bottomAnchor, constant: 20),
            replaceLabel2.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            replaceLabel2.widthAnchor.constraint(equalToConstant: 80),
            
            // 第二组替换输入框约束
            replaceTextField2.topAnchor.constraint(equalTo: replaceLabel2.topAnchor),
            replaceTextField2.leadingAnchor.constraint(equalTo: replaceLabel2.trailingAnchor, constant: 10),
            replaceTextField2.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            
            // 监听开关约束
            monitoringEnabledCheckbox.topAnchor.constraint(equalTo: replaceTextField2.bottomAnchor, constant: 20),
            monitoringEnabledCheckbox.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            
            // 替换模式约束
            replaceAllCheckbox.topAnchor.constraint(equalTo: monitoringEnabledCheckbox.bottomAnchor, constant: 10),
            replaceAllCheckbox.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            
            // 状态标签约束
            statusLabel.topAnchor.constraint(equalTo: replaceAllCheckbox.bottomAnchor, constant: 20),
            statusLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
    }
    
    private func startClipboardMonitoring() {
        // 获取当前剪贴板的changeCount
        lastChangeCount = NSPasteboard.general.changeCount
        
        // 创建定时器，每0.5秒检查一次剪贴板
        clipboardTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
            self?.checkClipboard()
        }
        
        isMonitoringEnabled = true
        monitoringEnabledCheckbox.state = .on
        updateStatus("剪贴板监听已启动")
    }
    
    @objc private func toggleMonitoring() {
        isMonitoringEnabled = (monitoringEnabledCheckbox.state == .on)
        
        if isMonitoringEnabled {
            if clipboardTimer == nil {
                // 如果定时器不存在，重新创建
                clipboardTimer = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
                    self?.checkClipboard()
                }
            }
            updateStatus("剪贴板监听已启动")
        } else {
            // 停止定时器但不销毁
            clipboardTimer?.invalidate()
            clipboardTimer = nil
            updateStatus("剪贴板监听已停止", isError: true)
        }
    }
    
    @objc private func toggleReplaceMode() {
        replaceAllOccurrences = (replaceAllCheckbox.state == .on)
        updateStatus(replaceAllOccurrences ? "将替换所有匹配项" : "将仅替换第一个匹配项")
    }
    
    private func checkClipboard() {
        // 如果监听被禁用，则不处理
        guard isMonitoringEnabled else { return }
        
        let pasteboard = NSPasteboard.general
        
        // 检查剪贴板是否有变化
        if pasteboard.changeCount != lastChangeCount {
            lastChangeCount = pasteboard.changeCount
            
            // 获取剪贴板中的字符串
            if let clipboardString = pasteboard.string(forType: .string) {
                processClipboardContent(clipboardString)
            }
        }
    }
    
    private func processClipboardContent(_ content: String) {
        // 获取第一组查找和替换的文本
        let findText = findTextField.stringValue
        let replaceText = replaceTextField.stringValue
        
        // 获取第二组查找和替换的文本
        let findText2 = findTextField2.stringValue
        let replaceText2 = replaceTextField2.stringValue
        
        // 初始化处理后的内容为原始内容
        var processedContent = content
        var hasReplaced = false
        
        // 处理第一组替换规则
        if !findText.isEmpty && content.contains(findText) {
            // 根据替换模式选择替换方法
            if replaceAllOccurrences {
                // 替换所有匹配项
                processedContent = processedContent.replacingOccurrences(of: findText, with: replaceText)
            } else {
                // 仅替换第一个匹配项
                if let range = processedContent.range(of: findText) {
                    processedContent = processedContent.replacingCharacters(in: range, with: replaceText)
                }
            }
            hasReplaced = true
            updateStatus("已替换: \"\(findText)\" → \"\(replaceText)\"")
        }
        
        // 处理第二组替换规则
        if !findText2.isEmpty && processedContent.contains(findText2) {
            // 根据替换模式选择替换方法
            if replaceAllOccurrences {
                // 替换所有匹配项
                processedContent = processedContent.replacingOccurrences(of: findText2, with: replaceText2)
            } else {
                // 仅替换第一个匹配项
                if let range = processedContent.range(of: findText2) {
                    processedContent = processedContent.replacingCharacters(in: range, with: replaceText2)
                }
            }
            hasReplaced = true
            updateStatus("已替换: \"\(findText2)\" → \"\(replaceText2)\"")
        }
        
        // 如果有替换发生，将处理后的内容写回剪贴板
        if hasReplaced {
            let pasteboard = NSPasteboard.general
            pasteboard.clearContents()
            pasteboard.setString(processedContent, forType: .string)
        } else if findText.isEmpty && findText2.isEmpty {
            updateStatus("请输入要查找的内容", isError: true)
        }
    }
    
    private func updateStatus(_ message: String, isError: Bool = false) {
        statusLabel.stringValue = message
        statusLabel.textColor = isError ? .systemRed : .systemGreen
    }
    
    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }
    
    deinit {
        // 停止定时器
        clipboardTimer?.invalidate()
    }
}

